<?php
// +----------------------------------------------------------------------
// | Created by PHPstorm: [ JRK丶Admin ]
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2022 [LuckyHHY] All rights reserved.
// +----------------------------------------------------------------------
// | SiteUrl: http://www.luckyhhy.cn
// +----------------------------------------------------------------------
// | Author: LuckyHhy <jackhhy520@qq.com>
// +----------------------------------------------------------------------
// | Date: 2020/7/17 0026
// +----------------------------------------------------------------------
// | Description:
// +----------------------------------------------------------------------


namespace app\common\subscribes;

use app\api\service\JinDie;
use app\api\service\message;
use app\common\energyApi\Energy;
use app\common\model\tang\Config;
use app\common\model\tang\Merchant;
use app\common\model\tang\KwhWaterLog;
use app\common\model\tang\MerchantDayMoney;
use app\common\model\tang\MerchantMoney;
use app\common\model\tang\MerchantMonthMoney;
use app\common\model\tang\MerchantOperate;
use app\common\model\tang\MerchantReadingLog;
use app\common\model\tang\MonthWaterLog;
use app\common\model\tang\WatchMaintain;
use think\facade\Log;

class WaterSubscribe extends Base
{
    /**
     * 定时执行的方法
     */
    public function onWater()
    {
        $start_time = strtotime(date('Y-m-d ' . '06:00:00'));
        $end_time = strtotime(date('Y-m-d ' . '07:40:00'));
        $YesterDay = date("Y-m-d", strtotime("-1 day"));
        $month = date("Y-m", strtotime("-1 month"));
        $monthss = date("Y-m", strtotime("-2 month"));
        $nowMonth = date("Y-m");
        $day = explode('-',$YesterDay);
        $mon = explode('-',$nowMonth);
        if($day[1]<$mon[1]){
            $nowMonth =$month;
        }
        $jin = new JinDie();
        $config = new Config();
        $message = new message();
        $merchantDayModel = new MerchantDayMoney();
        $MerchantMonthMoney = new MerchantMonthMoney();
        $merchant_list = (new MerchantOperate())->find(1);
        // 当前时间是否为 00：10 - 00:40
        if (time() >= $start_time && time() <= $end_time) {
            $configInfo = $config->find(1)->toArray();
            $money = (new MerchantMoney())->where('dateTime', $month)->find();
            // 查询所有商户
            $Allmerchant = (new WatchMaintain())->with(['merchant'])->where(['type'=>2,'status'=>1])->select()->toArray();
            if (!empty($Allmerchant)) {
                foreach ($Allmerchant as $item) {
                    //查询前一天是否记录
                    $log = (new KwhWaterLog())->where(['datelog' => $YesterDay, 'pointId' => $item['pointId']])->find();
                    if (empty($log)) {
                        $dandata = [
                            "water_or_electricity" => 1,
                            'type' => 3,
                            'day_month' => 2,
                            'pointId' => $item['point'],
                            'startdate' => $YesterDay,
                            'enddate' => ''
                        ];
                        // 查询月电费接口
//                        $port_data = $Energy->universalfunction('query_YWGPointWaterUsed_info', $data);
                        $port_data = $jin->getElectricity($dandata);
                        if(empty($port_data)){
                            $port_data = $jin->getElectricity($dandata);
                        }
                        if (!empty($port_data)) {
                            if (empty($port_data['endbm'])&&empty($port_data['startbm'])) {

                            } else {
                                $data = [
                                    'merchant_id' => $item['merchant_id'],
                                    'pointId' => $item['pointId'],
                                    'start' => $port_data['startbm'],
                                    'end' => $port_data['endbm'],
                                    'dataTime' => $nowMonth,
                                    'create_time' => time(),
                                    'datelog' => $YesterDay,
                                    'type' => 2,
                                ];
                                (new KwhWaterLog())->save($data);
                                if (in_array($item['merchant_id'],explode(',',$merchant_list['merchant_ids']))) {//指定用户催费
                                    if (!empty($money)) {
                                        $price = (new MonthWaterLog())->where(['pointId'=>$item['pointId']])->value('price');
                                        if(empty($price))$price = 3.4;
                                        $frozen_balance = bcmul(bcsub($port_data['endbm'], $port_data['startbm'], 2), $price, 2);
                                        if ($item['balance'] > 0 && !empty($item['merchant_id'])) {
                                            $balance = bcsub($item['balance'], $frozen_balance * 100);
                                            $add_frozen = bcadd($item['frozen_balance'], $frozen_balance * 100);

//                                    //查今天是否有记录
                                            $dayInfo = $merchantDayModel->where(['merchant_id' => $item['merchant_id'],'pointId'=>$item['pointId'], 'day' => $YesterDay])->find();
                                            $monthInfo = $MerchantMonthMoney->where(['merchant_id' => $item['merchant_id'], 'dataTime' => $nowMonth])->find();
                                            if (empty($dayInfo)) {
                                                (new Merchant())->where('id', $item['merchant_id'])->update(['balance' => $balance]);
                                                (new Merchant())->where('id', $item['merchant_id'])->update(['frozen_balance'=>$add_frozen]);
                                                $merchantDay['merchant_id'] = $item['merchant_id'];
                                                $merchantDay['code'] = $item['code'];
                                                $merchantDay['pointId'] = $item['pointId'];
                                                $merchantDay['balance']  = $item['balance'];
                                                $merchantDay['use_yue']  = $balance;
                                                $merchantDay['name']  = $item['name'];
                                                $merchantDay['company']  = $item['company'];
                                                $merchantDay['water_money']  = $frozen_balance * 100;
                                                $merchantDay['dataTime']  = $nowMonth;
                                                $merchantDay['day'] = $YesterDay;
                                                $merchantDay['create_time'] = time();
                                                $merchantDayModel->insert($merchantDay);
                                                if(empty($monthInfo)){
                                                    unset($merchantDay['day']);
                                                    unset($merchantDay['pointId']);
                                                    $MerchantMonthMoney->insert($merchantDay);
                                                }else{
                                                    $MerchantMonthMoney->update([
                                                        'water_money' => bcadd($monthInfo['water_money'], bcmul($frozen_balance, 100)),
                                                        'balance' => bcadd($item['balance'],$item['frozen_balance']),
                                                        'use_yue' => $balance,
                                                    ], ['id' => $monthInfo['id']]);
                                                }
                                            }
//                                            else {
//                                                $yingMoney = bcadd($dayInfo['water_money'], bcmul($frozen_balance, 100));
//                                                $merchantDayModel->update([
//                                                    'water_money' => $yingMoney,
//                                                    'balance' => bcadd($item['balance'],$item['frozen_balance']),
//                                                    'use_yue' => $balance,
//                                                    'is_send' => 0,
//                                                ], ['id' => $dayInfo['id']]);
//                                                $MerchantMonthMoney->update([
//                                                    'water_money' => bcadd($monthInfo['water_money'], bcmul($frozen_balance, 100)),
//                                                    'balance' => bcadd($item['balance'],$item['frozen_balance']),
//                                                    'use_yue' => $balance,
//                                                ], ['id' => $monthInfo['id']]);
//                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (in_array($item['merchant_id'],explode(',',$merchant_list['merchant_ids']))) {//指定用户催费
                        $water = $merchantDayModel->where(['merchant_id' => $item['merchant_id'], 'day' => $YesterDay, 'is_send' => 0])->sum('money');
                        $ele = $merchantDayModel->where(['merchant_id' => $item['merchant_id'], 'day' => $YesterDay, 'is_send' => 0])->sum('water_money');
                        $yesMoney = $water+$ele;
                        if ($yesMoney>0) {
                            if ($item['balance'] < bcmul($yesMoney, $configInfo['date_time'])) {
                                $senddata['company'] = $item['company'];
                                $senddata['balance'] = $item['balance'] / 100;
                                $senddata['openid'] = $item['openid'];
                                $message->arrearage($senddata);
                                $merchantDayModel->update(['is_send' => 1], ['merchant_id' =>$item['merchant_id'],'day' => $YesterDay]);
                            }
                        }
                    }
                    //获取上月第一天和现在时间
                    $waterLog = (new MonthWaterLog())->where(['dataTime' => $month, 'pointId' => $item['pointId']])->find();
                    $lastlog = (new MonthWaterLog())->order('dataTime desc')->where([ 'pointId' => $item['pointId']])->find();
                    if (time() >= strtotime(date('Y-m-03')) && time() <= strtotime(date('Y-m-12'))) {//时间处于当月1号10分到1点10分之间
                    $monthdata = [
                        "water_or_electricity" => 1,
                        'type' => 3,
                        'day_month' => 3,
                        'pointId' => $item['point'],
                        'startdate' => $month,
                        'enddate' => ''
                    ];
                        $port_data_month = $jin->getElectricity($monthdata);
                        if(empty($port_data_month)){
                            $port_data_month = $jin->getElectricity($monthdata);
                        }
                        if (empty($waterLog)) {
                            if (!empty($port_data_month['endbm'])&&!empty($port_data_month['startbm'])) {
                                if(!empty($lastlog)){
                                    $port_data_month['startbm'] = $lastlog['end'];
                                }
                                if($port_data_month['startbm']>$port_data_month['endbm']){
                                    $len = strlen($port_data_month['startbm']);
                                    if($len==4){
                                        $end = 9999;
                                    }else{
                                        $end = 99999;
                                    }
                                    $water = [
                                        'start' => $port_data_month['startbm'],
                                        'end' => $end,
                                        'pointId' => $item['pointId'],
                                        'merchant_id' => $item['merchant_id'],
                                        'dataTime' => $month,
                                        'create_time' => time()
                                    ];
                                    $port_data_month['startbm'] = 0;
                                    (new MonthWaterLog())->save($water);
                                }
                                $water = [
                                    'start' => $port_data_month['startbm'],
                                    'end' => $port_data_month['endbm'],
                                    'pointId' => $item['pointId'],
                                    'merchant_id' => $item['merchant_id'],
                                    'dataTime' => $month,
                                    'create_time' => time()
                                ];
                                (new MonthWaterLog())->save($water);
                            }
//                            if (!empty($port_data_month)) {
//                                if (!empty($port_data['endbm'])&&!empty($port_data['startbm'])) {
//                                    if(isset($lastlog)){
//                                        if($port_data_month['startbm']<$lastlog['end']){
//                                            $len = strlen($lastlog['end']);
//                                            if($len==4){
//                                                $end = 9999;
//                                            }else{
//                                                $end = 9999;
//                                            }
//                                            $water = [
//                                                'start' => $lastlog['end'],
//                                                'end' => $end,
//                                                'pointId' => $item['pointId'],
//                                                'merchant_id' => $item['merchant_id'],
//                                                'dataTime' => $month,
//                                                'create_time' => time()
//                                            ];
//                                            (new MonthWaterLog())->save($water);
//                                        }
//                                    }
//                                    $water = [
//                                        'start' => $port_data_month['startbm'],
//                                        'end' => $port_data_month['endbm'],
//                                        'pointId' => $item['pointId'],
//                                        'merchant_id' => $item['merchant_id'],
//                                        'dataTime' => $month,
//                                        'create_time' => time()
//                                    ];
//                                    (new MonthWaterLog())->save($water);
//                                }
//                            }
                        }else{
                            //是否有入离场
                            $is_reading_log = (new MerchantReadingLog())->where(['pointId'=>$item['pointId'],'in_type'=>1])->find();
                            $is_reading_month = (new MonthWaterLog())->where(['dataTime'=>$month,'merchant_id'=>$item['merchant_id'],'pointId'=>$item['pointId']])->find();
                            if(!empty($is_reading_log)&&empty($is_reading_month)){
                                $water_first = [
                                    'start' => $is_reading_log['sole'],
                                    'end' => $port_data_month['endbm'],
                                    'pointId' => $item['pointId'],
                                    'merchant_id' => $item['merchant_id'],
                                    'dataTime' => $month,
                                    'create_time' => time()
                                ];
                                Log::info('入场二次记录:'.json_encode($water_first));
                                (new MonthWaterLog())->save($water_first);
                            }
                        }
                    }
                }
            }
        }
    }
}